import React, { useState, useEffect, useRef } from 'react'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import './Lgoin.css'
import { AiOutlineWechat, AiOutlineQq, AiOutlineEye, AiOutlineEyeInvisible } from 'react-icons/ai'
import axios from 'axios'
import LoginLanguageSelector from '../../components/LoginLanguageSelector'

export default function Lgoin() {
  const { t } = useTranslation()
  const [showPassword, setShowPassword] = useState(false)
  const [loginType, setLoginType] = useState('password') // 'password' 或 'code'
  const [loginForm, setLoginForm] = useState({
    phone: '', // 用于手机号、邮箱或用户名
    password: '',
    verificationCode: ''
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [countdown, setCountdown] = useState(0)
  
  // 二次验证相关状态
  const [securityVerification, setSecurityVerification] = useState({
    required: false,
    tempToken: '',
    methods: [],
    selectedMethod: '',
    verificationData: '',
    isRiskUser: false,
    riskReason: '',
    location: null,
    loading: false
  })
  const timerRef = useRef(null)
  
  const navigate = useNavigate()
  const location = useLocation()
  
  // 获取重定向前的路径，如果没有则默认为首页
  const from = location.state?.from?.pathname || '/'

  // 判断输入是手机号还是邮箱
  const isPhoneNumber = (input) => {
    // 中国大陆手机号格式：1开头的11位数字
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(input);
  };

  const isEmail = (input) => {
    // 邮箱基本格式检查
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(input);
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setLoginForm({
      ...loginForm,
      [name]: value
    })
    // 清除错误信息
    if (error) setError('')
  }

  // 发送登录验证码
  const sendLoginCode = async () => {
    const userInput = loginForm.phone.trim();
    
    if (!userInput) {
      setError(t('login.errors.enterPhoneOrEmail'))
      return
    }

    // 判断是手机号还是邮箱
    let type = 'phone';
    if (isEmail(userInput)) {
      type = 'email';
    } else if (!isPhoneNumber(userInput)) {
      setError(t('login.errors.enterValidPhoneOrEmail'))
      return
    }

    try {
      setCountdown(60)
      setError('')
      
      const response = await axios.post('http://localhost:3001/lxt/send-verification-code', {
        type: 'phone',
        target: loginForm.phone.trim(),
        purpose: 'login'
      })

      if (response.data.code === 200) {
        console.log(`登录验证码已发送到${type === 'phone' ? '手机' : '邮箱'}`)
      } else {
        throw new Error(response.data.msg || '发送失败')
      }
    } catch (err) {
      setCountdown(0)
      console.error('发送验证码失败:', err)
      
      if (err.response && err.response.data && err.response.data.msg) {
        setError(`发送失败: ${err.response.data.msg}`)
      } else {
        setError(t('login.errors.sendCodeFailed'))
      }
    }
  }

  const handleLogin = async (e) => {
    e.preventDefault()
    
    // 表单验证
    if (loginType === 'password') {
      if (!loginForm.phone.trim() || !loginForm.password.trim()) {
        setError(t('login.errors.fillRequired'))
        return
      }
    } else {
      if (!loginForm.phone.trim() || !loginForm.verificationCode.trim()) {
        setError(t('login.errors.fillPhoneCode'))
        return
      }
      if (!isPhoneNumber(loginForm.phone.trim())) {
        setError(t('login.errors.invalidPhone'))
        return
      }
    }

    // 判断输入类型和登录方式
    const userInput = loginForm.phone.trim();
    let requestData = { loginType };

    if (loginType === 'password') {
      requestData.password = loginForm.password;
      
      if (isPhoneNumber(userInput)) {
        requestData.phone = userInput;
      } else if (isEmail(userInput)) {
        requestData.email = userInput;
      } else {
        // 如果既不是手机号也不是邮箱，视为用户名
        requestData.username = userInput;
      }
    } else {
      // 验证码登录
      if (isPhoneNumber(userInput)) {
        requestData.phone = userInput;
      } else if (isEmail(userInput)) {
        requestData.email = userInput;
      } else {
        setError(t('login.errors.enterValidPhoneOrEmail'));
        return;
      }
      requestData.verificationCode = loginForm.verificationCode;
    }
    
    try {
      setLoading(true)
      setError('')
      
      console.log('发送登录请求，参数:', requestData);
      
      // 发送登录请求
      const response = await axios.post('http://localhost:3001/lxt/login', requestData);
      
      console.log('登录响应:', response.data)
      
      // 检查是否需要二次验证 (状态码 202)
      if (response.status === 202 && response.data.requiresSecurityVerification) {
        console.log('需要二次验证:', response.data);
        
        setSecurityVerification({
          required: true,
          tempToken: response.data.tempToken,
          methods: response.data.verificationMethods || [],
          selectedMethod: response.data.verificationMethods?.[0]?.type || '',
          verificationData: '',
          isRiskUser: response.data.isRiskUser || false,
          riskReason: response.data.riskReason || '',
          location: response.data.location || null,
          loading: false
        });
        
        setError(''); // 清除错误信息
        return; // 不继续执行登录流程
      }
      
      // 检查响应中是否包含token
      if (response.data && response.data.token) {
        // 直接保存服务器返回的token，无需添加前缀
        const token = response.data.token;
        localStorage.setItem('token', token);
        
        // 如果有用户信息，也保存起来
        if (response.data.userInfo) {
          localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
        }
        
        console.log('登录成功，即将跳转到:', from)
        
        // 登录成功后跳转
        navigate(from, { replace: true })
      } else {
        // 响应中没有token
        console.error('登录响应缺少token:', response.data)
        setError('登录失败: 服务器响应格式错误')
      }
    } catch (err) {
      console.error('登录请求失败:', err)
      
      // 处理不同类型的错误
      if (err.response) {
        // 服务器返回了错误状态码
        const statusCode = err.response.status
        const responseData = err.response.data
        
        if (statusCode === 202 && responseData.requiresSecurityVerification) {
          // 处理二次验证请求
          console.log('捕获到二次验证请求:', responseData);
          
          setSecurityVerification({
            required: true,
            tempToken: responseData.tempToken,
            methods: responseData.verificationMethods || [],
            selectedMethod: responseData.verificationMethods?.[0]?.type || '',
            verificationData: '',
            isRiskUser: responseData.isRiskUser || false,
            riskReason: responseData.riskReason || '',
            location: responseData.location || null,
            loading: false
          });
          
          setError(''); // 清除错误信息
        } else if (statusCode === 401) {
          // 认证失败（用户名或密码错误）
          setError(t('login.errors.wrongCredentials'))
        } else if (responseData && responseData.msg) {
          // 服务器返回了错误消息
          setError(`登录失败: ${responseData.msg}`)
        } else {
          // 其他服务器错误
          setError(`${t('login.errors.serverError')} (${statusCode})`)
        }
      } else if (err.request) {
        // 请求发送了但没有收到响应
        setError(t('login.errors.networkError'))
      } else {
        // 请求设置时发生错误
        setError('登录失败: ' + err.message)
      }
    } finally {
      setLoading(false)
    }
  }

  // 发送二次验证码
  const sendSecurityCode = async () => {
    try {
      setSecurityVerification(prev => ({ ...prev, loading: true }));
      
      const response = await axios.post('http://localhost:3001/lxt/send-security-code', {
        tempToken: securityVerification.tempToken,
        verificationType: securityVerification.selectedMethod
      });
      
      if (response.data.code === 200) {
        alert(response.data.msg);
      } else {
        setError(response.data.msg);
      }
    } catch (err) {
      console.error('发送二次验证码失败:', err);
      setError(t('security.verificationFailed'));
    } finally {
      setSecurityVerification(prev => ({ ...prev, loading: false }));
    }
  };

  // 提交二次验证
  const submitSecurityVerification = async () => {
    if (!securityVerification.verificationData.trim()) {
      setError(t('security.enterVerification'));
      return;
    }

    try {
      setSecurityVerification(prev => ({ ...prev, loading: true }));
      setError('');

      const verificationPayload = {
        tempToken: securityVerification.tempToken,
        verificationType: securityVerification.selectedMethod,
        verificationData: {}
      };

      // 根据验证方式构造数据
      if (securityVerification.selectedMethod === 'password') {
        verificationPayload.verificationData.password = securityVerification.verificationData;
      } else {
        verificationPayload.verificationData.code = securityVerification.verificationData;
      }

      const response = await axios.post('http://localhost:3001/lxt/security-verification', verificationPayload);

      if (response.data.code === 200 && response.data.token) {
        // 验证成功，保存token并跳转
        localStorage.setItem('token', response.data.token);
        if (response.data.user) {
          localStorage.setItem('userInfo', JSON.stringify(response.data.user));
        }
        
        console.log('二次验证成功，即将跳转到:', from);
        navigate(from, { replace: true });
      } else {
        setError(response.data.msg || '验证失败');
      }
    } catch (err) {
      console.error('二次验证失败:', err);
      if (err.response && err.response.data && err.response.data.msg) {
        setError(err.response.data.msg);
      } else {
        setError(t('security.verificationFailed'));
      }
    } finally {
      setSecurityVerification(prev => ({ ...prev, loading: false }));
    }
  };

  // 取消二次验证，返回登录表单
  const cancelSecurityVerification = () => {
    setSecurityVerification({
      required: false,
      tempToken: '',
      methods: [],
      selectedMethod: '',
      verificationData: '',
      isRiskUser: false,
      riskReason: '',
      location: null,
      loading: false
    });
    setError('');
  };

  const handleThirdPartyLogin = async (platform) => {
    try {
      setLoading(true)
      setError('')
      
      console.log(`使用${platform}登录`)
      
      // 转换平台名称为API参数
      const typeMap = {
        '微信': 'wechat',
        'QQ': 'qq',
        'wechat': 'wechat',
        'qq': 'qq'
      }
      const type = typeMap[platform] || platform.toLowerCase()
      
      // 调用水滴聚合登录API获取登录链接
      const response = await axios.get(`http://localhost:3001/lxt/shuidi-login?type=${type}`)
      
      if (response.data && response.data.code === 200 && response.data.loginUrl) {
        console.log(`✅ 获取${platform}登录链接成功`)
        
        // 在原窗口跳转到登录链接
        window.location.href = response.data.loginUrl
        
      } else {
        throw new Error(response.data?.msg || '获取登录链接失败')
      }
      
    } catch (err) {
      console.error(`${platform}登录出错:`, err)
      
      if (err.response && err.response.data && err.response.data.msg) {
        setError(`${platform}登录失败: ${err.response.data.msg}`)
      } else {
        setError(`${platform}登录失败，请稍后再试`)
      }
    } finally {
      setLoading(false)
    }
  }

  // 倒计时逻辑
  useEffect(() => {
    if (countdown > 0) {
      timerRef.current = setTimeout(() => {
        setCountdown(countdown - 1)
      }, 1000)
    }

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current)
      }
    }
  }, [countdown])

  // 如果需要二次验证，显示验证界面
  if (securityVerification.required) {
    return (
      <div className="login-container">
        {/* 语言选择器 - 固定在右上角 */}
        <LoginLanguageSelector />
        
        <div className="login-form-wrapper">
          <div className="login-form">
            <div className="login-header">
              <h2>{t('security.title')}</h2>
              <span className="close-btn" onClick={cancelSecurityVerification}>{t('security.back')}</span>
            </div>

            <div className="security-verification-content">
              {securityVerification.isRiskUser && (
                <div className="risk-user-notice">
                  <div className="risk-icon">⚠️</div>
                  <div className="risk-text">
                    <strong>{t('security.riskUser')}</strong>
                    <p>{securityVerification.riskReason}</p>
                  </div>
                </div>
              )}

              {securityVerification.location && !securityVerification.isRiskUser && (
                <div className="location-notice">
                  <div className="location-icon">📍</div>
                  <div className="location-text">
                    <strong>{t('security.abnormalLogin')}</strong>
                    <p>检测到您从 {securityVerification.location.current} 登录</p>
                  </div>
                </div>
              )}

              <div className="verification-method-selector">
                <label>{t('security.selectMethod')}</label>
                <select 
                  value={securityVerification.selectedMethod}
                  onChange={(e) => setSecurityVerification(prev => ({
                    ...prev,
                    selectedMethod: e.target.value,
                    verificationData: ''
                  }))}
                  className="verification-method-select"
                >
                  {securityVerification.methods.map(method => (
                    <option key={method.type} value={method.type}>
                      {method.label} {method.target && `(${method.target})`}
                    </option>
                  ))}
                </select>
              </div>

              <div className="verification-input-group">
                {securityVerification.selectedMethod === 'password' ? (
                  <input
                    type="password"
                    placeholder={t('security.enterPassword')}
                    value={securityVerification.verificationData}
                    onChange={(e) => setSecurityVerification(prev => ({
                      ...prev,
                      verificationData: e.target.value
                    }))}
                    className="verification-input"
                  />
                ) : (
                  <div className="code-input-group">
                    <input
                      type="text"
                      placeholder={t('security.enterCode')}
                      value={securityVerification.verificationData}
                      onChange={(e) => setSecurityVerification(prev => ({
                        ...prev,
                        verificationData: e.target.value
                      }))}
                      className="verification-input"
                    />
                    <button
                      type="button"
                      onClick={sendSecurityCode}
                      disabled={securityVerification.loading}
                      className="send-code-btn"
                    >
                      {securityVerification.loading ? t('security.sending') : t('security.sendCode')}
                    </button>
                  </div>
                )}
              </div>

              {error && <div className="error-message">{error}</div>}

              <div className="verification-buttons">
                <button
                  type="button"
                  onClick={submitSecurityVerification}
                  disabled={securityVerification.loading || !securityVerification.verificationData.trim()}
                  className="verify-btn"
                >
                  {securityVerification.loading ? t('security.verifying') : t('security.verify')}
                </button>
                <button
                  type="button"
                  onClick={cancelSecurityVerification}
                  className="cancel-btn"
                >
                  {t('security.cancel')}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="login-container">
      {/* 语言选择器 - 固定在右上角 */}
      <LoginLanguageSelector />
      
      <div className="login-form-wrapper">
        <div className="login-form">
          <div className="login-header">
            <h2>{t('login.title')}</h2>
            <span className="close-btn">{t('login.close')}</span>
          </div>

          <div className="login-type-selector">
            <div
              className={`login-type-option ${loginType === 'password' ? 'active' : ''}`}
              onClick={() => setLoginType('password')}
            >
              {t('login.passwordLogin')}
            </div>
            <div
              className={`login-type-option ${loginType === 'code' ? 'active' : ''}`}
              onClick={() => setLoginType('code')}
            >
              {t('login.codeLogin')}
            </div>
          </div>
          
          {error && (
            <div className="error-alert">
              {error}
            </div>
          )}
          
          <form onSubmit={handleLogin}>
            <div className="form-group">
              <input
                type="text"
                name="phone"
                value={loginForm.phone}
                onChange={handleInputChange}
                placeholder={loginType === 'code' ? t('login.phonePlaceholder') : t('login.phoneEmailPlaceholder')}
                required
                disabled={loading}
              />
            </div>
            
            {loginType === 'password' ? (
              <div className="form-group password-group">
                <input
                  type={showPassword ? "text" : "password"}
                  name="password"
                  value={loginForm.password}
                  onChange={handleInputChange}
                  placeholder={t('login.passwordPlaceholder')}
                  required
                  disabled={loading}
                />
                <span 
                  className="toggle-password" 
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? <AiOutlineEye /> : <AiOutlineEyeInvisible />}
                </span>
              </div>
            ) : (
              <div className="form-group verification-group">
                <div className="verification-input-group">
                  <input
                    type="text"
                    name="verificationCode"
                    value={loginForm.verificationCode}
                    onChange={handleInputChange}
                    placeholder={t('login.codePlaceholder')}
                    maxLength={6}
                    required
                    disabled={loading}
                  />
                  <button
                    type="button"
                    className="verification-code-btn"
                    onClick={sendLoginCode}
                    disabled={countdown > 0 || loading}
                  >
                    {countdown > 0 ? `${countdown}${t('login.getCodeRetry')}` : t('login.getCode')}
                  </button>
                </div>
              </div>
            )}
            <button 
              type="submit" 
              className="login-btn"
              disabled={loading}
            >
              {loading ? t('login.loginButtonLoading') : t('login.loginButton')}
            </button>
          </form>
          <div className="form-footer">
            <span className="forgot-password">
              <Link to="/reset-password">{t('login.forgotPassword')}</Link>
            </span>
            <span className="register-link">
              <Link to="/zhuce">{t('login.register')}</Link>
            </span>
          </div>
          <div className="third-party-login">
            <p>{t('login.thirdPartyLogin')}</p>
            <div className="third-party-icons">
              <div 
                className={`third-party-icon wechat ${loading ? 'disabled' : ''}`}
                onClick={() => !loading && handleThirdPartyLogin('微信')}
                title={t('login.wechatLogin')}
              >
                <AiOutlineWechat size={24} />
              </div>
              <div 
                className={`third-party-icon qq ${loading ? 'disabled' : ''}`}
                onClick={() => !loading && handleThirdPartyLogin('QQ')}
                title={t('login.qqLogin')}
              >
                <AiOutlineQq size={24} />
              </div>
            </div>
            <div className="agreement-text">
              {t('login.agreement')} <Link to="/terms">{t('login.serviceTerms')}</Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
